<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="培训" data-page-identification="r_r40a0k0zas">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_hludvvyuwr 自定义模板_e9v1m4bggb -->
            <a-modal
                title="预览"
                :footer="null"
                v-model:visible="previewState.previewVisible"
                @cancel="handleCancel"
                width="80vw"
                :body-style="{
                    maxHeight: '800px',
                    overflowY: 'auto'
                }"
                centered
                destroy-on-close
            >
                <div class="middle-div" v-if="previewState.isImagePreview">
                    <img class="middle-div" :src="previewState.previewImage" alt="附件" style="width: 100%" />
                </div>
                <div class="middle-div" v-if="previewState.isDocPreview">
                    <vue-office-docx
                        class="middle-div"
                        :src="previewState.previewFileUrl"
                        @rendered="renderedHandler"
                        @error="errorHandler"
                    />
                </div>
                <div v-if="previewState.isPdfPreview">
                    <vue-office-pdf
                        class="middle-div"
                        :src="previewState.previewFileUrl"
                        @rendered="renderedHandler"
                        @error="errorHandler"
                    />
                    <iframe v-if="false" :src="previewState.previewFileUrl" style="width: 100%; height: 800px"></iframe>
                </div>
                <div v-if="previewState.isExcelPreview">
                    <vue-office-excel
                        class="middle-div"
                        :src="previewState.previewFileUrl"
                        :options="options"
                        @rendered="renderedHandler"
                        @error="errorHandler"
                    />
                </div>
                <div v-show="previewState.isViedoPreview">
                    <video
                        class="middle-div"
                        :src="previewState.previewFileUrl"
                        id="video-player"
                        controls
                        autoplay
                        controlslist="nodownload"
                    ></video>
                </div>
            </a-modal>
            <!--          平台新建/编辑培训-->
            <a-modal
                :visible="pxState.handleTrainVisible"
                :title="pxState.platformTitle"
                width="800px"
                @ok="handleConfirmTrain"
                @cancel="trainCancel"
                maskClosable
                destroy-on-close
                centered
                :body-style="{
                    paddingBottom: 0
                }"
                :ok-button-props="{ loading: pxState.okLoading }"
            >
                <a-spin :spinning="trainLoading" tip="附件上传中，请稍后...">
                    <a-form ref="platTrainRef" :model="pxState.trainForm">
                        <div class="px-form">
                            <a-row>
                                <a-col :span="24">
                                    <a-form-item
                                        label="项目阶段"
                                        :rules="[{ required: true, message: '请选择项目阶段', trigger: 'blur' }]"
                                        name="templateStageId"
                                    >
                                        <a-select
                                            allow-clear
                                            show-search
                                            :options="pxState.templateStageIdList"
                                            placeholder="请选择"
                                            v-model:value="pxState.trainForm.templateStageId"
                                            :field-names="{ label: 'label', value: 'value' }"
                                            :filter-option="
                                                (input, option) => {
                                                    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                            "
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="24">
                                    <a-form-item
                                        label="序号"
                                        :rules="[
                                            { required: false },
                                            { pattern: /^[1-9]\d*$/, message: '请输入正整数' }
                                        ]"
                                        name="sort"
                                    >
                                        <a-input-number
                                            placeholder="请输入正整数"
                                            v-model:value="pxState.trainForm.sort"
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="24">
                                    <a-form-item
                                        label="课程名称"
                                        :rules="[{ required: true, message: '请输入课程名称', trigger: 'blur' }]"
                                        name="name"
                                    >
                                        <a-input v-model:value="pxState.trainForm.name" />
                                    </a-form-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="24">
                                    <a-form-item label="课程说明">
                                        <a-textarea v-model:value="pxState.trainForm.description" />
                                    </a-form-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-form-item label="课程文件" name="fileList">
                                    <!--                                  :rules="[{ required: true, message: '请上传附件', trigger: 'blur' }]"-->
                                    <a-upload
                                        v-model:file-list="pxState.trainForm.fileList"
                                        :multiple="true"
                                        :before-upload="handlerTrainUpload"
                                        @remove="handlerTrainRemove"
                                        accept=".xlsx, image/*,.docx,, .xls,.mp4,.zip,.rar"
                                    >
                                        <a-button type="primary">
                                            <upload-outlined />
                                            上传
                                        </a-button>
                                    </a-upload>
                                    <span>支持格式：.xlsx, image/*,.docx,, .xls,.mp4</span>
                                    <div class="tip">上传前对文件进行解密</div>
                                </a-form-item>
                            </a-row>
                            <div class="module-item" v-for="(item, index) in pxState.trainForm.videoList" :key="index">
                                <div class="form-content">
                                    <a-row>
                                        <a-col :span="12">
                                            <a-form-item
                                                label="视频名称"
                                                :rules="[
                                                    { required: false, message: '请输入视频名称', trigger: 'blur' }
                                                ]"
                                                :name="['videoList', index, 'videoName']"
                                            >
                                                <a-input
                                                    style="width: 100%"
                                                    v-model:value="pxState.trainForm.videoList[index].videoName"
                                                />
                                            </a-form-item>
                                        </a-col>
                                        <a-col :span="12">
                                            <a-form-item
                                                label="视频链接"
                                                :rules="[
                                                    { required: false, message: '请输入视频链接', trigger: 'blur' }
                                                ]"
                                                :name="['videoList', index, 'videoLinks']"
                                            >
                                                <a-input
                                                    v-model:value="pxState.trainForm.videoList[index].videoLinks"
                                                />
                                            </a-form-item>
                                        </a-col>
                                    </a-row>
                                </div>

                                <a class="del" @click="handlerDeleteFormItem1(index)">删除</a>
                                <a class="add-btn" @click="handlerAddFormItem1(index, '下方')">下方插入</a>
                            </div>
                            <a-row>
                                <a-col>
                                    <a-form-item>
                                        <a-button type="primary" ghost @click="handlerAddFormItem1(index, '最后')"
                                            ><template #icon><plus-outlined /></template>新增</a-button
                                        >
                                    </a-form-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="24">
                                    <a-form-item label="考试链接">
                                        <a-textarea v-model:value="pxState.trainForm.examLink" />
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </div>
                    </a-form>
                </a-spin>
            </a-modal>
            <!--          平台新建/编辑培训-->
            <div class="kb-page">
                <div class="table-body">
                    <div class="template-title">
                        <div class="title-left"><span class="title-font">课程列表</span> </div>
                        <div
                            ><a-space>
                                <a-button @click="getPlatformData" type="primary">查询</a-button>
                                <a-button
                                    @click="handleAddTrain"
                                    type="primary"
                                    v-permission="'3000000627_vid_2v0x7613mc'"
                                >
                                    <template #icon><PlusOutlined /></template> 新建</a-button
                                >
                            </a-space></div
                        >
                    </div>
                    <div class="top-tip-font">
                        <div class="weight-font-img"> </div>
                        <div class="color-jx"></div>
                        <div class="weight-font"> 含项目阶段： </div>
                        <div class="tip-normal-font"
                            >1. 部署工作准备；2. 硬件发货；3. 一键部署；4.产品初始化；5. 数据采集；6. 主数据映射；7.
                            数据处理；8.配料系统设置；9.自学习数据确认；10. 数据建模；11. 试运行；12. 正式运行；13.
                            验收</div
                        >
                    </div>
                    <div class="default-table">
                        <a-table
                            bordered
                            :columns="columns"
                            :loading="pxState.tableLodaing"
                            :data-source="pxState.platformData"
                            @resizeColumn="handleTaskResizeColumn"
                            :pagination="pagination"
                            :total="pagination.total"
                            :scroll="{ x: 'max-content', y: pxState.tableHeight }"
                        >
                            <template #bodyCell="{ column, record, text }">
                                <template v-if="column.dataIndex === 'opration'">
                                    <a-button
                                        type="link"
                                        size="small"
                                        v-permission="'3000000627_vid_6b6mzxwz2c'"
                                        @click="handleEditTrain(record)"
                                        >编辑</a-button
                                    >

                                    <a-popconfirm title="确定要删除吗？" @confirm="handleDeleteTrain(record)">
                                        <a-button v-permission="'3000000627_vid_qk8vgwconf'" size="small" type="link"
                                            >删除</a-button
                                        >
                                    </a-popconfirm>
                                </template>
                                <template v-if="column.dataIndex === 'file'">
                                    <div class="file-div" v-for="(item, index) in record.fileList">
                                        <a-dropdown>
                                            <span
                                                style="
                                                    width: 300px;
                                                    overflow: hidden;
                                                    white-space: nowrap;
                                                    text-overflow: ellipsis;
                                                    display: block;
                                                "
                                                :title="item.name"
                                            >
                                                {{ item.name }}
                                            </span>
                                            <template #overlay>
                                                <a-menu>
                                                    <a-menu-item v-if="isVideo(item.type)">
                                                        <a-button
                                                            style="width: 100%"
                                                            type="link"
                                                            size="small"
                                                            @click="showVideo(item.url)"
                                                            >预览</a-button
                                                        >
                                                    </a-menu-item>
                                                    <a-menu-item>
                                                        <a-button
                                                            style="width: 100%"
                                                            type="link"
                                                            size="small"
                                                            @click="handlerDownload(item)"
                                                            >下载</a-button
                                                        >
                                                    </a-menu-item>
                                                </a-menu>
                                            </template>
                                        </a-dropdown>
                                    </div>
                                </template>
                                <template v-if="column.dataIndex === 'videoName'">
                                    <template v-if="record.videoList.length > 0">
                                        <div
                                            v-for="(item, index) in record.videoList"
                                            @click="showVideo(item.videoLinks)"
                                            class="videolinks"
                                        >
                                            {{ item.videoName?.trim() }}
                                        </div>
                                    </template>
                                    <!--                                    <div class="video-name" @click="showVideo(record.videoLinks)"> {{ text }}</div>-->
                                </template>
                                <template v-if="column.dataIndex === 'examLink'">
                                    <template v-if="text">
                                        <div v-for="(item, index) in handlerGetSpace(text)" class="exam-link">
                                            <a
                                                :key="index"
                                                :href="item.trim()"
                                                style="
                                                    display: block;
                                                    width: 300px;
                                                    overflow: hidden;
                                                    white-space: nowrap;
                                                    text-overflow: ellipsis;
                                                    display: block;
                                                "
                                                rel="noopener noreferrer"
                                                target="_blank"
                                                >{{ item?.trim() }}</a
                                            >
                                        </div>
                                    </template>
                                </template>
                                <template v-if="column.dataIndex === 'description'">
                                    <template v-if="text">
                                        <div v-for="(item, index) in handlerGetSpace1(text)">
                                            {{ item?.trim() }}
                                        </div>
                                    </template>
                                </template>
                            </template>
                        </a-table>
                    </div>
                </div>
            </div>

            <a-modal
                :visible="pxState.videoVisble"
                width="885px"
                centered
                title="视频文件"
                @cancel="closeVideo"
                destroy-on-close
                :footer="null"
            >
                <div class="video-container">
                    <video
                        id="video01"
                        :src="pxState.videoSrc"
                        playsinline
                        webkit-playsinline
                        preload="auto"
                        autoplay
                        width="840"
                        height="360"
                    ></video>
                    <!--                    <div class="watermark"></div>-->
                </div>
            </a-modal>
            <!-- end vid_hludvvyuwr 自定义模板_e9v1m4bggb -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    import { nextTick } from 'vue'
    // import VueOfficePdf from '@vue-office/pdf'
    // import VueOfficeExcel from '@vue-office/excel'
    // import VueOfficeDocx from '@vue-office/docx'
    import TCPlayer from 'tcplayer.js'
    import 'tcplayer.js/dist/tcplayer.min.css'
    const previewState = reactive({
        previewVisible: false,
        previewImage: '',
        previewFileUrl: '',
        isImagePreview: false,
        isDocPreview: false,
        isPdfPreview: false,
        isExcelPreview: false,
        isViedoPreview: false
    })

    function previewAttachment(item) {
        if (item.type.startsWith('image')) {
            previewState.isExcelPreview = false
            previewState.isImagePreview = true
            previewState.isDocPreview = false
            previewState.isViedoPreview = false
            previewState.isPdfPreview = false
            previewState.previewImage = item.url // 设置预览图片的URL
            previewState.previewVisible = true // 显示模态框
        }
        // else if (isDocFile(item.name, '.pdf')) {
        //     nextTick(() => {
        //         previewState.previewVisible = true // 显示模态框
        //         previewState.previewFileUrl = item.url // 设置预览PDF的URL
        //         previewState.isImagePreview = false
        //         previewState.isDocPreview = false
        //         previewState.isViedoPreview = false
        //         previewState.isExcelPreview = false
        //         previewState.isPdfPreview = true
        //     })
        // }
        else if (isDocFile(item.name, '.doc')) {
            previewState.isImagePreview = false
            previewState.isDocPreview = true
            previewState.isViedoPreview = false
            previewState.isPdfPreview = false
            previewState.isExcelPreview = false
            previewState.previewFileUrl = item.url // 设置预览WORD的URL
            previewState.previewVisible = true // 显示模态框
        } else if (isDocFile(item.name, '.docx')) {
            previewState.isExcelPreview = false
            previewState.isImagePreview = false
            previewState.isViedoPreview = false
            previewState.isDocPreview = true
            previewState.isPdfPreview = false
            previewState.previewFileUrl = item.url // 设置预览WORD的URL
            previewState.previewVisible = true // 显示模态框
        } else if (isDocFile(item.name, '.xls')) {
            options.value.xls = true
            previewState.isViedoPreview = false
            previewState.isImagePreview = false
            previewState.isDocPreview = false
            previewState.isPdfPreview = false
            previewState.isExcelPreview = true
            previewState.previewFileUrl = item.url // 设置预览EXCEL的URL
            previewState.previewVisible = true // 显示模态框
        } else if (isDocFile(item.name, '.xlsx')) {
            options.value.xls = false
            previewState.isImagePreview = false
            previewState.isDocPreview = false
            previewState.isPdfPreview = false
            previewState.isViedoPreview = false
            previewState.isExcelPreview = true
            previewState.previewFileUrl = item.url // 设置预览EXCEL的URL
            previewState.previewVisible = true // 显示模态框
        } else if (item.type.startsWith('video')) {
            options.value.xls = false
            previewState.isImagePreview = false
            previewState.isDocPreview = false
            previewState.isPdfPreview = false
            previewState.isViedoPreview = true
            previewState.isExcelPreview = false
            previewState.previewFileUrl = item.url // 设置预览EXCEL的URL
            // previewState.previewVisible = true // 显示模态框
            nextTick(() => {
                let video = document.querySelector('#video-player')
                console.log(video)
                video?.requestFullscreen()
            })
        } else {
            message.warning('暂不支持预览的文件格式，请下载查看')
        }
    }
    function handlerDownload(item) {
        pageLoading.loading = true
        pageLoading.tip = '文件下载中...'
        fetch(item.url)
            .then(response => response.blob())
            .then(blob => {
                const downloadLink = document.createElement('a')
                const url = URL.createObjectURL(blob)
                downloadLink.href = url
                downloadLink.setAttribute('download', item.name)
                downloadLink.style.display = 'none'
                document.body.appendChild(downloadLink)
                downloadLink.click()
                document.body.removeChild(downloadLink)

                // Release the object URL after the download
                URL.revokeObjectURL(url)
                pageLoading.loading = false
            })
            .catch(err => {
                console.error('Download failed', err)
            })
    }

    function isDocFile(fileName, str) {
        return fileName.toLowerCase().endsWith(str)
    }

    function handleCancel() {
        previewState.isExcelPreview = false
        previewState.isImagePreview = false
        previewState.isDocPreview = false
        previewState.isViedoPreview = false
        previewState.isPdfPreview = false
        previewState.previewVisible = false // 显示模态框
    }

    function renderedHandler() {
        message.success('渲染成功')
    }

    function errorHandler(e) {
        message.error('渲染失败')
        console.log(e)
    }

    const options = ref({
        xls: true, //预览xlsx文件设为false；预览xls文件设为true
        minColLength: 0, // excel最少渲染多少列，如果想实现xlsx文件内容有几列，就渲染几列，可以将此值设置为0.
        minRowLength: 0, // excel最少渲染多少行，如果想实现根据xlsx实际函数渲染，可以将此值设置为0.
        widthOffset: 10, //如果渲染出来的结果感觉单元格宽度不够，可以在默认渲染的列表宽度上再加 Npx宽
        heightOffset: 10 //在默认渲染的列表高度上再加 Npx高
    })
    const activeKey = ref('项目筹备')
    const radioValue = ref('1')
    const pxState = reactive({
        auth: false,
        tableHeight: 600,
        tableLodaing: false,
        searchForm: {
            projectName: undefined,
            version: undefined,
            milepostName: undefined,
            taskName: undefined,
            taskId: undefined,
            milepostId: undefined
        },
        taskList: [],
        regionList: [],
        miltpostList: [],
        projectNameList: [],
        versionList: [],
        //   平台表格数据
        platformData: [],
        // 模板表格数据
        templateData: [],
        //   模板新建表单
        handleTrainVisible: false,
        platformTitle: '',
        trainForm: {
            projectName: undefined,
            sort: undefined,
            version: undefined,
            description: undefined,
            fileList: [],
            type: undefined,
            templateTaskId: undefined,
            templateStageId: undefined,
            templateTaskId: undefined,
            examLink: undefined,
            name: undefined,
            videoName: undefined,
            videoLinks: undefined,
            videoList: []
        },
        videoVisble: false,
        videoSrc: '',
        templateStageIdList: [],
        okLoading: false
    })
    const videoItem = {
        videoLinks: undefined,
        videoName: undefined
    }
    const trainLoading = ref(false)
    const columns = ref([
        {
            title: '体系',
            dataIndex: 'label',
            align: 'left',
            width: 150
        },
        {
            title: '项目阶段',
            dataIndex: 'templateStageName',
            align: 'left',
            width: 150,
            customCell: item => {
                const { rowIndex, rowSpan } = item
                return {
                    rowSpan: rowSpan,
                    style: {
                        fontSize: '16px',
                        color: '#262626',
                        fontWeight: '600'
                        // borderTop: rowIndex ? '1px solid #3875ff' : 'none'
                    }
                }
            }
        },
        {
            title: '序号',
            dataIndex: 'sort',
            align: 'left',
            width: 150
        },
        {
            title: '课程名称',
            dataIndex: 'name',
            align: 'left',
            ellipsis: true,
            resizable: true,
            width: 280
        },
        {
            title: '课程说明',
            dataIndex: 'description',
            align: 'left',
            ellipsis: true,
            resizable: true,
            width: 280
        },
        {
            title: '课程文件',
            dataIndex: 'file',
            align: 'left',
            width: 300
        },
        {
            title: '视频文件',
            dataIndex: 'videoName',
            align: 'left',
            width: 300
        },
        {
            title: '考试链接',
            dataIndex: 'examLink',
            align: 'left',
            width: 300
        },
        {
            title: '操作人',
            dataIndex: 'updateBy',
            align: 'left',
            ellipsis: true,
            resizable: true,
            width: 130
        },
        {
            title: '最新更新时间',
            dataIndex: 'updateTime',
            align: 'left',
            ellipsis: true,
            resizable: true,
            width: 150
        },
        {
            title: '操作',
            dataIndex: 'opration',
            align: 'center',
            width: 130,
            fixed: 'right'
        }
    ])
    const templateColumns = ref([
        {
            title: '项目阶段',
            dataIndex: 'milepostName',
            align: 'center',
            ellipsis: true,
            resizable: true,
            width: 280
        },
        {
            title: '任务名称',
            dataIndex: 'taskName',
            align: 'center',
            ellipsis: true,
            resizable: true,
            width: 280
        },
        {
            title: '课程说明',
            dataIndex: 'description',
            align: 'center',
            ellipsis: true,
            resizable: true,
            width: 280
        },
        {
            title: '课程文件',
            dataIndex: 'file',
            align: 'center',
            resizable: true,
            width: 300
        },
        {
            title: '最新操作人',
            dataIndex: 'updateBy',
            align: 'center',
            ellipsis: true,
            resizable: true,
            width: 130
        },
        {
            title: '最新提交时间',
            dataIndex: 'updateTime',
            align: 'center',
            ellipsis: true,
            resizable: true,
            width: 150
        },
        {
            title: '操作',
            dataIndex: 'opration',
            align: 'center',
            width: 130
        }
    ])

    //删除一个模块
    function handlerDeleteFormItem1(index) {
        if (pxState.trainForm.videoList.length == 1) {
            return
        }
        pxState.trainForm.videoList.splice(index, 1)
    }
    // 新插一条模块
    function handlerAddFormItem1(index, type) {
        if (type === '最后') {
            pxState.trainForm.videoList.push({ ...videoItem })
        } else {
            // 否则使用 splice 方法在 index 后插入
            pxState.trainForm.videoList.splice(index + 1, 0, { ...videoItem })
        }
    }
    // 获取平台产品培训列表
    function getPlatformData() {
        pxState.tableLodaing = true
        post('/solution-ppm/api/v2/built-in-system-ppm/train/milepost/search', {
            ...pxState.searchForm,
            pageNo: pagination.value.current,
            pageSize: pagination.value.pageSize
        })
            .then(data => {
                processingData(data, 'platformData', null)
            })
            .finally(() => {
                pxState.tableLodaing = false
            })
    }

    //     获取平台项目项目名称
    function getProjectList() {
        post('/solution-ppm/api/v2/built-in-system-ppm/train/platform_project', {}).then(data => {
            processingData(data, 'projectNameList', null)
        })
    }

    // 处理数据及异常
    function processingData(data, target, msg) {
        if (data.code === 200) {
            if (!target) {
                message.success(msg)
            } else {
                if (data.data.dataList !== undefined) {
                    pxState[target] = groupData(data.data.dataList)
                    pagination.value.total = data.data.totalElements
                } else {
                    pxState[target] = data.data
                }
            }
            return true
        } else {
            message.error(data.message)
            return false
        }
    }

    //     新建课程
    function handleAddTrain() {
        if (!pxState.auth) {
            message.info('暂无权限')
            return
        }
        pxState.trainForm.videoList = [{ ...videoItem }]
        pxState.handleTrainVisible = true
        pxState.trainForm.type = 3
        pxState.platformTitle = '新建课程内容'
    }

    //     新建课程
    function handleTaskResizeColumn(w, col) {
        col.width = w
    }

    //     编辑课程
    function handleEditTrain(record) {
        if (!pxState.auth) {
            message.info('暂无权限')
            return
        }
        let newData = cloneDeep(record)

        // 遍历pxState.trainForm的键并赋值
        for (let key in pxState.trainForm) {
            if (newData.hasOwnProperty(key)) {
                pxState.trainForm[key] = newData[key]
            }
        }
        pxState.trainForm.id = newData.id
        if (activeKey.value !== '平台产品') {
            pxState.trainForm.type = 3
        }
        pxState.handleTrainVisible = true
        pxState.platformTitle = '编辑课程内容'
    }

    //     编辑课程

    // 删除课程
    function handleDeleteTrain(record) {
        if (!pxState.auth) {
            message.info('暂无权限')
            return
        }
        del(`/solution-ppm/api/v2/built-in-system-ppm/train/${record.id}`).then(data => {
            if (processingData(data, false, '删除成功')) {
                getPlatformData()
            }
        })
    }

    // 删除课程

    //     平台新建/编辑保存
    const platTrainRef = ref(null)

    function handleConfirmTrain() {
        if (!pxState.trainForm.id) {
            // 新建
            platTrainRef.value
                .validate()
                .then(() => {
                    pxState.okLoading = true
                    post('/solution-ppm/api/v2/built-in-system-ppm/train', pxState.trainForm).then(data => {
                        if (processingData(data, false, '新建成功')) {
                            getPlatformData()
                            pxState.handleTrainVisible = false
                            resetData(pxState.trainForm)
                        }
                    })
                })
                .finally(() => {
                    pxState.okLoading = false
                })
        } else {
            //   编辑保存
            platTrainRef.value.validate().then(() => {
                pxState.okLoading = true
                put('/solution-ppm/api/v2/built-in-system-ppm/train', pxState.trainForm)
                    .then(data => {
                        if (processingData(data, false, '编辑成功')) {
                            getPlatformData()
                            pxState.handleTrainVisible = false
                            resetData(pxState.trainForm)
                        }
                    })
                    .finally(() => {
                        pxState.okLoading = false
                    })
            })
        }
    }

    function trainCancel() {
        pxState.handleTrainVisible = false
        resetData(pxState.trainForm)
    }
    function resetData(data) {
        for (let key in data) {
            if (data.hasOwnProperty(key)) {
                if (Array.isArray(data[key])) {
                    data[key] = []
                } else if (typeof data[key] === 'object' && data[key] !== null) {
                    data[key] = {}
                } else {
                    if (key === 'pageSize') {
                        data[key] = 999999
                    } else if (key === 'pageNo') {
                        data[key] = 1
                    } else if (key === 'templateName') {
                        data[key] = activeKey.value
                    } else {
                        data[key] = undefined
                    }
                }
            }
        }
        return data // 返回重置后的数据
    }
    const count = ref([])
    const successCount = ref(0)

    // 上传文件
    function handlerTrainUpload(file) {
        count.value.push(file)
        trainLoading.value = true
        const data = new FormData()
        data.append('file', file)

        post('/file-storage/api/v1/file/upload', data)
            .then(({ data: { fullUrl } }) => {
                successCount.value++
                if (data) {
                    // 新文件对象
                    const newFile = {
                        uid: file.uid,
                        lastModified: file.lastModified,
                        name: file.name,
                        size: file.size,
                        type: file.type,
                        status: 'done',
                        url: fullUrl
                    }

                    // 去重，保留一个副本
                    pxState.trainForm.fileList = [
                        // 保留已存在文件（去除重复）
                        ...pxState.trainForm.fileList.filter(item => item.uid !== file.uid && item.name !== file.name),
                        // 添加新的文件
                        newFile
                    ]
                }
            })
            .catch(e => {
                message.error('上传失败' + e)
            })
            .finally(() => {
                if (successCount.value == count.value.length) {
                    trainLoading.value = false
                    successCount.value = 0
                    count.value = []
                }
            })

        return false
    }

    // 移除文件
    function handlerTrainRemove(file) {
        pxState.trainForm.fileList = pxState.trainForm.fileList.filter(item => item.uid !== file.uid)
    }
    function handlerGetSpace(data) {
        return data ? data.split(/[,，]/).map(item => item.trim()) : []
    }
    function handlerGetSpace1(data) {
        return data ? data.split(/[,，;；\n]/).map(item => item.trim()) : []
    }
    let player = ref(null) // 在外部作用域声明播放器实例
    function showVideo(record) {
        console.log(record)
        pxState.videoVisble = true
        pxState.videoSrc = record
        nextTick(() => {
            localStorage.setItem('ghostWatermarkFirstShow', 0)
            let userInfo = localStorage.getItem('al__USER_INFO')
            console.log(JSON.parse(userInfo).value)
            let userName = JSON.parse(userInfo).value.name
            player.value = TCPlayer('video01', {
                sources: [
                    {
                        src: pxState.videoSrc // 播放地址
                    }
                ],
                licenseUrl: 'https://license.vod2.myqcloud.com/license/v2/1309773370_1/v_cube.license', // license 地址，参考准备工作部分，在视立方控制台申请 license 后可获得 licenseUrl
                plugins: {
                    DynamicWatermark: {
                        //
                        type: 'text',
                        speed: 0.3, // 建议取值范围 0<= speed <=1，默认值 0.2
                        content: `研究院版权所有（${userName}正在播放）`, // 添加换行符
                        opacity: 0.5,
                        fontSize: '12px', // type === text 时有效, 其余字段通用
                        color: '#FFFFFF'
                    }
                }
            })
        })
    }
    // 分页方法
    const pageSizeChange = (current, size) => {
        pagination.value.current = current
        pagination.value.pageSize = size
        getPlatformData()
    }
    const pageChange = (page, pageSize) => {
        pagination.value.current = page
        pagination.value.pageSize = pageSize
        getPlatformData()
    }
    onMounted(() => {
        getPlatformData()
        getTemplateStageIdList()
        get('/solution-ppm/api/v2/built-in-system-ppm/train/permission').then(data => {
            pxState.auth = data.data
        })
    })
    function getTemplateStageIdList() {
        get('/solution-ppm/api/v2/built-in-system-ppm/task/faq/v2/project_stage').then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            pxState.templateStageIdList = data.data.map(item => {
                return {
                    label: item.stageName,
                    value: item.templateStageId
                }
            })
        })
    }
    function closeVideo() {
        player.value?.dispose()
        pxState.videoVisble = false // 关闭弹窗
    }
    const pagination = ref({
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
        total: '0',
        pageSizeOptions: ['5', '10', '20', '30', '40', '100'],
        showTotal: total =>
            `共 ${total} 个项目 第${pagination.value.current}/${Math.ceil(
                pagination.value.total / pagination.value.pageSize
            )}页`,
        onShowSizeChange: pageSizeChange,
        onChange: pageChange
    })
    function groupData(data) {
        let templateStageName = ''
        if (!data || !data.length) {
            return []
        }
        return data.map((item, index) => {
            if (templateStageName !== item.templateStageName) {
                templateStageName = item.templateStageName
                let rowSpan = 0
                for (let i = 0; i < data.length; i++) {
                    if (i >= index) {
                        if (templateStageName === data[i].templateStageName) {
                            rowSpan += 1
                        } else {
                            break
                        }
                    }
                }
                item.rowSpan = rowSpan
                item.border = index
            } else {
                item.rowSpan = 0
            }
            item.rowIndex = index
            return item
        })
    }
    const isVideo = fileType => {
        // 判断文件类型是否为视频
        return /^video\//.test(fileType)
    }
    const headerOffset = ref(170)
    const calcTableHeight = () => {
        pxState.tableHeight = window.innerHeight - 150 - headerOffset.value
    }

    onMounted(() => {
        calcTableHeight()
        window.addEventListener('resize', calcTableHeight)
    })

    onBeforeUnmount(() => {
        window.removeEventListener('resize', calcTableHeight)
    })
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .page_root {
        overflow: hidden;
    }
    .search-div {
        background-color: #fff;
        margin-bottom: 16px;
        height: 72px;
        padding: 0 20px;
        border-radius: 6px;
    }
    .default-table:deep(.@{ant-prefix}-table-thead) > tr > th {
        background-color: #3875ff;
        color: #fff;
        font-weight: 600;
        padding: 8px 16px;
        border-right: 1px solid #d9d9d9;
    }
    .default-table:deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #262626;
        padding: 8px 16px;
        border-bottom: 1px solid #d9d9d9;
        word-break: break-all;
    }
    .kb-page {
        padding-top: 16px;
        padding: 20px;
        height: 100%;
        position: relative;
        background-color: #fff;
        border-radius: 6px;
    }
    .template-title {
        margin-top: 10px;
        padding-left: 8px;
        font-size: 16px;
        height: 16px;
        line-height: 16px;
        font-weight: 800px;
        border-left: 4px solid #3875ff;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }
    .title-font {
        font-weight: 800;
    }
    .title-left {
        display: flex;
        gap: 16px;
    }
    .title-tip {
    }
    :deep(.ant3-input-number) {
        width: 100%;
    }
    :deep(.px-form .ant3-form-item-label) {
        width: 80px !important;
    }
    .file-div {
        color: #3875ff;
        cursor: pointer;
    }
    .tip {
        font-weight: 800;
    }
    .middle-div {
        margin: 0 auto;
    }

    .videolinks {
        width: 300px;
        cursor: pointer;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        color: #3875ff;
    }
    .video-container {
        width: 100%;
        position: relative;
        display: inline-block;
    }
    .watermark {
        position: absolute;
        color: rgba(255, 255, 255, 0.7);
        background-color: rgba(0, 0, 0, 0.5);
        padding: 5px;
        border-radius: 5px;
        font-size: 14px;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        pointer-events: none; /* 确保水印不会影响视频的交互 */
    }
    .video-name {
        cursor: pointer;
        color: #3875ff;
    }
    .top-tip {
        font-size: 14px;
        color: #262626;
        letter-spacing: 0;
        text-align: justify;
        font-weight: 400;
        background: rgba(250, 100, 0, 0.1);
        border: 1px solid #fa6400;
        border-radius: 2px;
        padding: 6px 16px;
        margin-bottom: 24px;
    }
    .tip-img {
        width: 16px;
        height: 16px;
        color: #fa6400;
    }
    .module-item,
    .module-item-two {
        position: relative;
        width: calc(100% - 60px);
    }
    .add-btn {
        position: absolute;
        right: -35px;
        color: #3875ff;
        top: 5px;
    }
    .form-content {
        display: inline-block;
        width: calc(100% - 80px);
    }
    .del {
        width: 28px;
        color: #3875ff;
        position: absolute;
        right: 35px;
        top: 5px;
    }
    .exam-link {
        width: 300px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        display: block;
    }
    .weight-font-img {
        background-image: url('http://10.40.0.33:9001/file-storage/492793474816894976-source.png');
        background-size: cover;
        height: 24px;
        width: 24px;
    }
    .top-tip-font {
        display: flex;
        gap: 8px;
        margin-bottom: 18px;
        position: relative;
    }
    .color-jx {
        position: absolute;
        width: 115px;
        height: 4px;
        background-image: linear-gradient(269deg, rgba(105, 173, 255, 0) 1%, #3875ff 100%);
        bottom: 0;
    }
    .weight-font {
        font-size: 14px;
        color: #262626;
        text-align: center;
        font-weight: 500;
    }
    .tip-normal-font {
        font-size: 14px;
        color: #262626;
        font-weight: 400;
    }
</style>
